from Store import Store
import pytc
class TCStore(Store):
    # Types
    HASHTABLE = 1
    BTREE = 2
    
    # Modes
    READ_ONLY = 1
    READ_WRITE = 2
    TRUNC = 4

    def __init__(self, filename, mode=READ_WRITE, type=BTREE):
        self._dbFile = filename
        self._mode = mode
        self._db = self._createDBObject(filename, mode, type)

    def put(self, key, value):
        self._db.put(key, value)


    def get(self, key):
        return self._db.get(key)


    def delete(self, key):
        return Store.delete(self, key)


    def flush(self):
        return Store.flush(self)


    def close(self):
        return Store.close(self)

        
    def _createDBObject(self, filename, mode=READ_WRITE, type=BTREE):
        if type == TCStore.HASHTABLE: 
            db = pytc.HDB()
            if mode == TCStore.READ_ONLY:
                db_mode = pytc.HDBOREADER
            elif mode == TCStore.READ_WRITE:
                db_mode = pytc.HDBOWRITER
            elif mode == TCStore.TRUNC:
                db_mode = pytc.HDBOTRUNC
            else:
                raise Exception("Unknown TC mode!")
        elif type == TCStore.BTREE:
            db = pytc.BDB()            
            if mode == TCStore.READ_ONLY:
                db_mode = pytc.BDBOREADER
            elif mode == TCStore.READ_WRITE:
                db_mode = pytc.BDBOWRITER | pytc.BDBOCREAT
            elif mode == TCStore.TRUNC:
                db_mode = pytc.BDBOTRUNC
            else:
                raise Exception("Unknown TC mode!")
        else:
            raise Exception("Unknown TC Type!")
        db.open(filename, db_mode)
        return db